package lumis.portal.deployment;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Enumeration;

import org.apache.xbean.classloader.JarFileClassLoader;

/**
 * Class loader used for JAR library modules.
 *
 * @version $Revision: 12533 $ $Date: 2011-02-07 17:23:32 -0200 (Mon, 07 Feb 2011) $
 * @since 5.0.0
 */
class JarLibraryModuleClassLoader extends JarFileClassLoader
{
	/**
	 * Specifies classes that cannot be overridden in this class loader. Contains
	 * the start of the classes fully qualified name.
	 * @since 5.0.0
	 */
	private static final String[] nonOverridableClasses = { "java.", "javax.", "lumis." };
	
	/**
	 * Returns the URL for a local file.
	 * @param file the file.
	 * @return the URL.
	 * @since 5.0.0
	 */
	private static URL getURL(File file)
	{
		try
		{
			return file.toURI().toURL();
		}
		catch (MalformedURLException e)
		{
			throw new IllegalArgumentException("Could not convert '" + file + "' to a URL");
		}
	}
	
	public JarLibraryModuleClassLoader(File archiveFile)
	{
		super(archiveFile.toString(), new URL[] { getURL(archiveFile) }, 
				JarLibraryModuleClassLoader.class.getClassLoader(), true, 
				new String[0], nonOverridableClasses);
	}

	@Override
	public Class<?> findClass(String name) throws ClassNotFoundException
	{
		return super.findClass(name);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public Enumeration<URL> findResources(String resourceName) throws IOException
	{
		return super.findResources(resourceName);
	}

	/**
	 * Returns the class with the given binary name if it has been loaded
	 * by this class loader. 
	 * @param name the name of the class.
	 * @return the class, or <code>null</code> if it has not been loaded by 
	 * this class loader.
	 * @since 5.0.0
	 */
	public Class<?> findClassIfLoaded(String name)
	{
		return findLoadedClass(name);
	}
}